package com.gao.security.verificationcode;

import com.gao.security.verificationcode.base.BaseCode;
import com.gao.security.verificationcode.base.BaseCodeOperationManager;
import com.gao.security.verificationcode.base.VerficationCode;
import com.gao.security.verificationcode.exception.ValidateCodeIncorrectException;
import com.gao.security.verificationcode.exception.ValidateCodeTimeoutException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.core.AuthenticationException;

/**
 * <p></p>
 *
 * @author GaoShuangWen
 * @since 2019-07-29 15:45
 */
@Slf4j
public class VerficationCodeProviderManager implements VerficationCodeManager {

    private BaseCodeOperationManager strategy;

    @Override
    public boolean verification(VerficationCode verficationCode) throws AuthenticationException {
        BaseCode codeObject = strategy.getCodeObject(verficationCode.getUuid());
        if(codeObject==null||System.currentTimeMillis()<codeObject.getExpireTime()){
            throw new ValidateCodeTimeoutException("ValidateCode timeout");
        }
        if(!verficationCode.getCode().equals(codeObject.getCode())){
            throw new ValidateCodeIncorrectException("ValidateCode error");
        }
        return true;
    }

    public void setStrategy(BaseCodeOperationManager strategy) {
        this.strategy = strategy;
    }
}
